package com.sjh.lib_update;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * author : SunJH
 * date   : 2021/5/7 0007
 * desc   : 静默安装app的工具类
 */
public class InstallApp {
    private static String TAG = InstallApp.class.getSimpleName();
    public static InstallApp getInstance(){
        return new InstallApp();
    }
    public void install28(Context context, File apkFile) {
        new Thread(() -> {
            Log.d(TAG, "install28 path=" + apkFile.getPath());
            PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
            PackageInstaller.SessionParams sessionParams
                    = new PackageInstaller.SessionParams(PackageInstaller
                    .SessionParams.MODE_FULL_INSTALL);
            sessionParams.setSize(apkFile.length());

            int sessionId = createSession(packageInstaller, sessionParams);
            Log.d(TAG, "install28  sessionId=" + sessionId);
            if (sessionId != -1) {
                boolean copySuccess = copyInstallFile(packageInstaller, sessionId, apkFile);
                Log.d(TAG, "install28  copySuccess=" + copySuccess);
                if (copySuccess) {
                    execInstallCommand(context, packageInstaller, sessionId);
                }
            }
        }).start();

    }

    private int createSession(PackageInstaller packageInstaller,
                              PackageInstaller.SessionParams sessionParams) {
        int sessionId = -1;
        try {
            sessionId = packageInstaller.createSession(sessionParams);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sessionId;
    }

    private boolean copyInstallFile(PackageInstaller packageInstaller,
                                    int sessionId,  File apkFile ) {
        InputStream in = null;
        OutputStream out = null;
        PackageInstaller.Session session = null;
        boolean success = false;
        try {
            session = packageInstaller.openSession(sessionId);
            out = session.openWrite("base.apk", 0, apkFile.length());
            in = new FileInputStream(apkFile);
            int total = 0, c;
            byte[] buffer = new byte[65536];
            while ((c = in.read(buffer)) != -1) {
                total += c;
                out.write(buffer, 0, c);
            }
            session.fsync(out);
            Log.i(TAG, "streamed " + total + " bytes");
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                in.close();
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return success;
    }

    private void execInstallCommand(Context context, PackageInstaller packageInstaller, int sessionId) {
        PackageInstaller.Session session = null;
        try {
            session = packageInstaller.openSession(sessionId);
            Intent intent = new Intent(context, InstallResultReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                    1, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            session.commit(pendingIntent.getIntentSender());
            Log.i(TAG, "begin session");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

}
